package com.mall.product.exception;

import com.mall.common.utils.Constant;
import com.mall.common.utils.BizCodeEnum;
import com.mall.common.utils.R;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;


@Slf4j
@RestControllerAdvice
public class ControllerExceptionAdvice {



    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public R handleHttpMessageNotReadableException(HttpMessageNotReadableException e){
        return  R.error(BizCodeEnum.HTTP_MSG_NOT_READABLE.getCode(), BizCodeEnum.HTTP_MSG_NOT_READABLE.getMsg());
    }


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        BindingResult result =  e.getBindingResult();
        HashMap<String,String> hashMap = new HashMap<>();
        if(result.hasFieldErrors()){
            result.getFieldErrors().forEach(item -> {
                hashMap.put(item.getField(), item.getDefaultMessage());
            });
        }
        return  R.error(BizCodeEnum.VILID_EXCEPTION.getCode(), BizCodeEnum.VILID_EXCEPTION.getMsg()).put(Constant.DATA,hashMap);
    }


}
